package myException.myRestfulGolbalException;


import lombok.Data;

import java.io.Serializable;

/**
 * 接口返回数据格式
 *
 * @author cc
 * @date 2021年11月03日
 */
@Data
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功标志
     */
    private boolean success = true;

    /**
     * 返回处理消息
     */
    private String message = "成功";

    /**
     * 返回代码
     */
    private String code = "200";

    /**
     * 返回数据对象 data
     */
    private T result;

    /**
     * 时间戳
     */
    private long timestamp = System.currentTimeMillis();

    public Result() {
    }

    public static <T> Result<T> success(String message) {
        Result<T> r = new Result<T>();
        r.setSuccess(true);
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage(message);
        return r;
    }

    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_OK_200);
        r.setResult(data);
        return r;
    }

    public static <T> Result<T> success(String msg, T data) {
        Result<T> r = new Result<T>();
        r.setCode(CommonConstant.SC_OK_200);
        r.setMessage(msg);
        r.setResult(data);
        return r;
    }

    public static Result<Object> error(String msg) {
        return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
    }

    public static Result<Object> error(BaseErrorInfoInterface e) {
        return error(e.getResultCode(), e.getResultMsg(), null);
    }

    public static Result<Object> error(BizException e) {
        return error(e.getCode(), e.getMsg());
    }

    public static Result<Object> error(BaseErrorInfoInterface e, Object data) {
        return error(e.getResultCode(), e.getResultMsg(), data);
    }

    public static Result<Object> error(String msg, Exception e) {
        return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg + e.getMessage());
    }

    public static Result<Object> error(String code, String msg) {
        return error(code, msg, null);
    }

    public static Result<Object> error500(String message) {
        return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, message);
    }

    public static <T> Result<T> error(String code, String msg, T data) {
        Result<T> r = new Result<>();
        r.setSuccess(false);
        r.setCode(code);
        r.setMessage(msg);
        r.setResult(data);
        return r;
    }

    private static <T> Result<T> error(Long code, String msg) {
        Result<T> r = new Result<>();
        r.setSuccess(false);
        r.setCode(code.toString());
        r.setMessage(msg);
        r.setResult(null);
        return r;
    }
}